<?php
include_once(dirname(__FILE__) . "/../config.php");

class Parser {
    private $mSummary = null;

    public function Parser($summary = array()) {
        if (empty($summary)) {
            $summary = array(
                "id" => 0,
                "name" => "",
                "title" => "",
                "info" => "",
            );
        }
        $this->mSummary = $summary;
    }

    public function id() {
        return $this->mSummary["id"];
    }

    public function name() {
        return $this->mSummary["name"];
    }

    public function title() {
        return $this->mSummary["title"];
    }

    public function info() {
        return $this->mSummary["info"];
    }

    public function setName($n) {
        $this->mSummary["name"] = $n;
    }

    public function setTitle($n) {
        $this->mSummary["title"] = $n;
    }

    public function setInfo($n) {
        $this->mSummary["info"] = $n;
    }


    public function save() {
        $id = $this->id();
        if ($id == 0) {
            $id = db_parser::inst()->add($this->name(), $this->title(), $this->info());
            if ($id !== false) {
                $this->mSummary["id"] = $id;
            }
        } else {
            $id = db_parser::inst()->modify($id, $this->name(), $this->title(), $this->info());
        }
        return $id;
    }

    public function packInfo() {
       return array(
            "id" => $this->id(),
            "name" => $this->name(), 
            "title" => $this->title(),
            "info" => $this->info(),
        );
    }

    public static function create($id) {
        $summary = db_parser::inst()->get($id);
        if (empty($summary)) {
            return null;
        }
        return new Parser($summary);
    }

    public static function all() {
        $items = db_parser::inst()->all();
        $arr = array();
        foreach ($items as $id => $summary) {
            $arr[$id] = new Parser($summary);
        }
        return $arr;
    }

    public static function &cachedAll() {
        $cache = cache::instance();
        $all = $cache->load("class.parser.all", null);
        if ($all === null) {
            $all = Parser::all();
            $cache->save("class.parser.all", $all);
        }
        return $all;
    }

    public static function remove($id) {
        return db_parser::inst()->remove($id);
    }
};

